package cn.codenest.springboot.mongo.dao.impl;

import cn.codenest.springboot.mongo.dao.UserDAO;
import cn.codenest.springboot.mongo.entity.UserEntity;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

@Component
public class UserDAOImpl implements UserDAO {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public void saveUser(UserEntity user) {
        mongoTemplate.save(user, UserEntity.COLLECTION_NAME);
    }

    @Override
    public void removeUser(Long id) {
        Query query = new Query(Criteria.where("id").is(id));//查找其id字段的值与传入参数id相等的数据
        DeleteResult re = mongoTemplate.remove(query, UserEntity.class, UserEntity.COLLECTION_NAME);
    }

    @Override
    public UserEntity findUserByName(String name) {
        Query query = new Query(Criteria.where("userName").is(name));
        UserEntity user = mongoTemplate.findOne(query, UserEntity.class, UserEntity.COLLECTION_NAME);
        return user;
    }

    @Override
    public int updateUser(UserEntity user) {
        Query query = new Query(Criteria.where("id").is(user.getId()));
        Update update = new Update().set("userName", user.getUserName()).set("password", user.getPassword());
        //更新查询返回的结果集的第一条数据
        UpdateResult result = mongoTemplate.updateFirst(query, update, UserEntity.class, UserEntity.COLLECTION_NAME);
        //更新查询到的所有结果集
        //UpdateResult all_result = mongoTemplate.updateMulti(query,update,User.class);
        if (result != null) {
            return (int) result.getModifiedCount();
        } else {
            return 0;
        }
    }
}
